# -*- coding: utf-8 -*-
"""
标签模块
"""
from flask import  Blueprint,render_template,request
from apps.common.curd import get_one_by_id
from apps.common.utils.http import table_api, success_api, fail_api
from apps.common.utils.validate import str_escape
from apps.common.utils.rights import authorize
from apps.extensions import db
from apps.modules.admin.models import Tag
from apps.modules.admin.schemas import TagOutSchema
import re
tag_bp = Blueprint('tag', __name__, url_prefix='/tag')

# 标签管理
@tag_bp.get('/')
@authorize("cms:tag:main")
def main():
    return render_template('cms/tag/main.html')


# 标签列表
@tag_bp.get('/data')
@authorize("cms:tag:main")
def table():
    title = str_escape(request.args.get('title', type=str))
    filters = []
    if title:
        filters.append(Tag.title.contains(title))
    tags = Tag.query.filter(*filters).layui_paginate()
    return table_api(data=TagOutSchema(many=True).dump(tags), count=tags.total)

# 标签增加
@tag_bp.get('/add')
@authorize("cms:tag:add", log=True)
def add():
    return render_template('cms/tag/add.html')

# 标签保存
@tag_bp.post('/save')
@authorize("cms:tag:add", log=True)
def save():
    req = request.get_json(force=True)

    data = {
        "title": str_escape(req.get("title")),
        "alias": str_escape(req.get("alias")),
        "desc": str_escape(req.get("desc"))
    }
    if not all(data.values()):
        return fail_api(msg="参数不足")

    # 验证必填字段
    if not data.get('title') or not data.get('alias'):
        return fail_api( '标签名称和别名不能为空')
        # 验证别名格式
    alias = data.get('alias')
    if not re.match(r'^[a-z0-9-]+$', alias):
        return fail_api('别名只能包含小写字母、数字和连字符')

    title = data.get('title')
    # 检查名称是否已存在
    existing_title = Tag.query.filter_by(title=title, deleted=False).first()
    if existing_title:
        return fail_api('名称已存在')
    # 检查别名是否已存在
    existing_alias = Tag.query.filter_by(alias=alias, deleted=False).first()
    if existing_alias:
        return fail_api('别名已存在')
    tag = Tag(**data)
    db.session.add(tag)
    db.session.commit()
    return success_api(msg="添加标签成功")

# 标签编辑
@tag_bp.get('/edit/<int:id>')
@authorize("cms:tag:edit", log=True)
def edit(id):
    tag = get_one_by_id(model=Tag, id=id)
    return render_template('cms/tag/edit.html', tag=tag)

# 更新标签
@tag_bp.put('/update')
@authorize("cms:tag:edit", log=True)
def update():
    req_json = request.get_json(force=True)
    id = req_json.get("tagId")

    data = {
        "title": str_escape(req_json.get("title")),
        "alias": str_escape(req_json.get("alias")),
        "desc": str_escape(req_json.get("desc"))
    }
    title = data.get('title')
    # 检查名称是否已被其他标签使用
    existing_title = Tag.query.filter(
        Tag.title == title,
        Tag.id != id,
        Tag.deleted == False
    ).first()
    if existing_title:
        return fail_api('名称已存在')

    # 验证别名格式（如果提供）
    if data.get('alias'):
        alias = data.get('alias')
        if not re.match(r'^[a-z0-9-]+$', alias):
            return fail_api('别名只能包含小写字母、数字和连字符')

        # 检查别名是否已被其他标签使用
        existing_alias = Tag.query.filter(
            Tag.alias == alias,
            Tag.id != id,
            Tag.deleted == False
        ).first()
        if existing_alias:
            return fail_api('别名已存在')
    tag = Tag.query.filter_by(id=id).update(data)
    db.session.commit()
    if not tag:
        return fail_api(msg="更新标签失败")

    return success_api(msg="更新标签成功")





# 标签删除
@tag_bp.delete('/remove/<int:id>')
@authorize("cms:tag:remove", log=True)
def remove(id):
    tag = Tag.query.filter_by(id=id).first()

    if not tag:
        return fail_api(msg="标签不存在")
    t = Tag.query.filter_by(id=id).delete()
    db.session.commit()
    if not t:
        return fail_api(msg="标签删除失败")
    return success_api(msg="标签删除成功")